package com.itheima.controller;


import com.itheima.common.R;
import com.itheima.dto.ChangeCategoryDTO;
import com.itheima.dto.InsertCategoryDTO;
import com.itheima.entity.Category;
import com.itheima.service.CategoryService;
import com.itheima.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author msi
 */
@RequestMapping("/category")
@RestController
public class CategoryController {
    @Autowired
    private CategoryService service;

    /**
     * 新增
     *
     * @param insertCategoryDTO
     * @return
     */
    @PostMapping("")
    public R insertCategory(@RequestBody InsertCategoryDTO insertCategoryDTO) {
        R r = new R();
        boolean flag = service.insertCategory(insertCategoryDTO);
        int code = flag ? 1 : 0;
        String msg = flag ? "新增成功" : "'分类名'已存在";
        r.setCode(code);
        r.setMsg(msg);

        return R.success("新增成功");
    }

    @PutMapping("")
    public R updateCategory(@RequestBody ChangeCategoryDTO changeCategoryDTO) {

        Boolean flag = service.update(changeCategoryDTO);


        return flag ? R.success(null) : R.error("修改失败");
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping
    public R deleteCategory(@RequestParam("id") String id) {
        R r = new R();
        if (id != null) {
            Boolean flag = service.deleteById(id);
            int i = flag ? 1 : 0;
            String msg = flag ? "信息删除成功" : "删除失败";
            r.setCode(i);
            r.setMsg(msg);
        }

        return r;
    }

    /**
     * 查询全部
     *
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> selectList(Integer type) {
        R<List<Category>> r = new R<>();
        List<Category> list = service.selectList(type);
        if (list != null && list.size() != 0) {
            r.setData(list);
            r.setCode(1);
        }

        return r;
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<ResultVO> selectPage(@RequestParam("page") Long page, @RequestParam("pageSize") Long pageSize) {

        ResultVO resultVO = service.selectPage(page, pageSize);

        R<ResultVO> r = new R<>();

        r.setData(resultVO);

        return R.success(resultVO);
    }
}
